package com.zlm.common.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 身份证信息算法类
 *
 * @author xhj
 *
 */
public class CardUtil {

    private static Pattern P1 =  Pattern.compile("(\\d{17}[0-9xX]|\\d{14}[0-9xX])");

    /**
     * 用于提取出生日字符串
     */
    private static Pattern P2 =  Pattern.compile("\\d{6}(\\d{8}).*");

    /**
     * 用于将生日字符串进行分解为年月日
     */
    private static Pattern P3 =  Pattern.compile("(\\d{4})(\\d{2})(\\d{2})");

    /**
     * 第一代身份证正则表达式(15位)
     */
    public static String IS_IDCARD1 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";

    /**
     * 第二代身份证正则表达式(18位)
     */
    public static String IS_IDCARD2 ="^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[A-Z])$";

    /**
     * 根据身份证的号码获取生日、年龄、性别
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getCardInfo(String card) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (!validate(card)) {
            map = null;
//            throw new Exception("身份证格式不正确");
        }

        if (card.length() == 15) {
            map = getCarInfo15W(card);
        }

        if (card.length() == 18) {
            map = getCarInfo18W(card);
        }

        return map;
    }

    /**
     * 检验身份证格式是否正确
     * @param card
     * @return
     */
    public static boolean validate(String card) {
        if (!checkSimple(card)) {
            return false;
        }

        if (!checkBirthday(card)) {
            return false;
        }

        if (!checkBit(card)) {
            return false;
        }

        return true;
    }

    /**
     * 18位身份证的验证
     * @param
     */
    private static Map<String, Object> getCarInfo18W(String card) {
        Map<String, Object> map = new HashMap<>();
        StringBuilder birthday = new StringBuilder();
        // 得到年份
        String year = card.substring(6).substring(0, 4);
        birthday.append(year).append("-");
        map.put("year", year);
        // 得到月份
        String month = card.substring(10).substring(0, 2);
        birthday.append(month).append("-");
        map.put("month", month);
        //得到日
        String day = card.substring(12).substring(0,2);
        birthday.append(day);
        map.put("day", day);
        map.put("birthday", DateTimeUtils.dateString2Date(birthday.toString(),
                DateTimeUtils.FORMAT_DATE_DEFAULT));

        Integer sex;
        if (Integer.parseInt(card.substring(16).substring(0, 1)) % 2 == 0) {
            // 判断性别
            sex = 0;
        } else {
            sex = 1;
        }
        // 得到当前的系统时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 当前年份
        String fyear = format.format(date).substring(0, 4);
        // 月份
        String fyue = format.format(date).substring(5, 7);
        // String fday=format.format(date).substring(8,10);
        Integer age = 0;
        if (Integer.parseInt(month) <= Integer.parseInt(fyue)) {
            // 当前月份大于用户出身的月份表示已过生
            age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
        } else {
            // 当前用户还没过生
            age = Integer.parseInt(fyear) - Integer.parseInt(year);
        }
        map.put("sex", sex);
        map.put("age", age);
        return map;
    }

    /**
     * 15位身份证的验证
     * @param
     */
    private static Map<String, Object> getCarInfo15W(String card) {
        Map<String, Object> map = new HashMap<>();
        StringBuilder birthday = new StringBuilder();
        // 年份
        String uyear = "19" + card.substring(6, 8);
        birthday.append(uyear).append("-");
        map.put("year", uyear);
        // 月份
        String uyue = card.substring(8, 10);
        birthday.append(uyue).append("-");
        map.put("month", uyue);
        //日
         String uday=card.substring(10, 12);
        birthday.append(uday).append("-");
        map.put("day", uday);
        map.put("birthday", DateTimeUtils.dateString2Date(birthday.toString(),
                DateTimeUtils.FORMAT_DATE_DEFAULT));

        // 用户的性别
        String usex = card.substring(14, 15);
        Integer sex;
        if (Integer.parseInt(usex) % 2 == 0) {
            sex = 0;
        } else {
            sex = 1;
        }
        // 得到当前的系统时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 当前年份
        String fyear = format.format(date).substring(0, 4);
        // 月份
        String fyue = format.format(date).substring(5, 7);
        // String fday=format.format(date).substring(8,10);
        Integer age = 0;
        if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) {
            // 当前月份大于用户出身的月份表示已过生
            age = Integer.parseInt(fyear) - Integer.parseInt(uyear) + 1;
        } else {
            // 当前用户还没过生
            age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
        }
        map.put("sex", sex);
        map.put("age", age);
        return map;
    }

    /**
     * 身份证长度校验
     * @param card
     * @return
     */
    private static boolean checkSimple(String card) {
        if (card != null && (card.matches(IS_IDCARD1) || card.matches(IS_IDCARD2))) {
            return true;
        }
        return false;
    }

    /**
     * 判断校验位是否正确
     * @param card
     * @return
     */
    private static boolean checkBit(String card) {
        // 1-17位相乘因子数组
        int[] factor = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
        // 18位随机码数组
        char[] random = "10X98765432".toCharArray();
        // 计算1-17位与相应因子乘积之和
        int total = 0;
        for (int i = 0; i < 17; i++)
        {
            total += Character.getNumericValue(card.charAt(i)) * factor[i];
        }
        // 判断随机码是否相等
        return random[total % 11] == card.charAt(17);
    }

    /**
     * 判断年月日是否正确
     * @param card
     * @return
     */
    private static boolean checkBirthday(String card) {
        Matcher matcher = P1.matcher(card);
        if (matcher.matches()) {
            Matcher matcher2 = P2.matcher(card);
            boolean flag = matcher2.find();
            if (flag) {
                String date = matcher2.group(1);
                Matcher matcher3 = P3.matcher(date);
                if (matcher3.find()) {
                    String year = matcher3.group(1);
                    int month = Integer.parseInt(matcher3.group(2));
                    int day = Integer.parseInt(matcher3.group(3));
                    if (month < 1 || month > 12) {
                        return false;
                    }
                    if (day > getDays(year, month) || day < 1) {
                        return false;
                    }
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断是否是闰年
     * @param year
     * @return
     */
    private static boolean isLeapYear(String year) {
        Long yearL = Long.parseLong(year);
        if ((yearL % 4 == 0) && (yearL % 100 != 0) || (yearL % 400 == 0)) {
            return true;
        }
        return false;
    }

    /**
     * 获取一年中某个月对应的天数
     * @param year
     * @param month
     * @return
     */
    private static int getDays(String year, int month) {
        int days = 0;
        switch (month) {
            case 1:
                days = 31;
                break;
            case 3:
                days = 31;
                break;
            case 5:
                days = 31;
                break;
            case 7:
                days = 31;
                break;
            case 8:
                days = 31;
                break;
            case 10:
                days = 31;
                break;
            case 12:
                days = 31;
                break;
            case 2:
                if (isLeapYear(year)) {
                    days = 29;
                } else {
                    days = 28;
                }
                break;
            default:
                days = 30;
        }
        return days;
    }
}
